package de.dopichaj.labrador.inex;


import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import de.dopichaj.labrador.inex.assess.Assessable;
import de.dopichaj.labrador.inex.assess.XCGAssessor;
import de.dopichaj.labrador.search.hit.DocHitMap;
import de.dopichaj.labrador.search.hit.Hit;


/**
 * Write a submission in INEX 2006 format.
 */
public final class SubmissionWriter {
    
    private static final int RESULT_COUNT = 1500;

    private static final Logger log = Logger.getLogger(SubmissionWriter.class);
    
    private final String collection;
    /**
     * The minimum length of a result to be in the "good" results.
     */
    private static final int MIN_LENGTH = 50;
    private final PathSanitizer pathSanitizer;
    private final PrintWriter writer;
    private final Map<Integer, XCGAssessor> assessorMap;
    private int topicCount = 0;
    private double[] nxcgSum = new double[RESULT_COUNT];
    
    public enum Task {
        THOROUGH, FOCUSED, ALL_IN_CONTEXT, BEST_IN_CONTEXT
    }
    
    /**
     * Create a new SubmissionWriter.
     * 
     * @param year the INEX submission format year
     * @param writer the writer to write to
     * @param type the type of the task (e. g. "CO")
     * @param task the task
     * @param id the ID to use (will be combined with task and type)
     * @param description the description of the run
     * @param assessor the assessor to use for immediate evaluation (may be <code>null</code>)
     */
    public SubmissionWriter(int year, Writer writer, String type,
        Task task, String id, String description, Map<Integer, XCGAssessor> assessorMap) {
        
        this.writer = new PrintWriter(writer);
        
        final int participantId;
        final String fullTask;
        if (year == 2005) {
            participantId = 12;
            final String taskString;
            switch (task) {
            case FOCUSED:
                taskString = "Focussed";
                break;
            case THOROUGH:
                taskString = "Thorough";
                break;
            case ALL_IN_CONTEXT:
                taskString = "FetchBrowse";
                break;
            default:
                throw new IllegalArgumentException("Invalid task: " + task);
            }
            if (type.equals("CO")) {
                fullTask = type + "." + taskString;
            } else {
                fullTask = "VVCAS";
            }
            collection = "ieee";
            pathSanitizer = new IEEEPathSanitizer();
        } else if (year == 2006 || year == 2007) {
            if (year == 2006) {
                participantId = 13;
                switch (task) {
                case FOCUSED:
                    fullTask = "Focused";
                    break;
                case THOROUGH:
                    fullTask = "Thorough";
                    break;
                case ALL_IN_CONTEXT:
                    fullTask = "AllInContext";
                    break;
                case BEST_IN_CONTEXT:
                    fullTask = "BestInContext";
                    break;
                default:
                    throw new IllegalArgumentException("Invalid task: " + task);
                }
            } else {
                participantId = 1;
                switch (task) {
                case FOCUSED:
                    fullTask = "Focused";
                    break;
                case ALL_IN_CONTEXT:
                    fullTask = "RelevantInContext";
                    break;
                case BEST_IN_CONTEXT:
                    fullTask = "BestInContext";
                    break;
                default:
                    throw new IllegalArgumentException("Invalid task: " + task);
                }
            }
            collection = "wikipedia";
            pathSanitizer = new WikipediaPathSanitizer();
        } else {
            throw new IllegalArgumentException("Invalid year for submission format");
        }

        println("<?xml version='1.0'?>");
        println("<inex-submission participant-id='" + participantId + "' " +
            "run-id='" + type + "." + id + "." + task + "' " +
            "task='" + fullTask + "' " +
            (year == 2007 ? "result-type='element' " : "") +
            "query='automatic'>");
        
        if (year == 2006 || year == 2007) {
            final boolean isCas = type.equals("CAS");
            println("  <topic-fields description='no' narrative='no' " +
                (year != 2007 ? "ontopic_keywords='no' " : "") +
                "title='" + (isCas ? "no" : "yes") + "' " +
                " castitle='" + (isCas ? "yes" : "no") + "'" +
                (year == 2007 ? " mmtitle='no'" : "") + "/>");
        }
        
        println("  <description>");
        println("    " + description +
            (task.equals("") ? "" : " (" + task + ")"));
        println("  </description>");

        println("  <collections>");
        println("    <collection>" + collection + "</collection>");
        println("  </collections>");
        
        this.assessorMap = assessorMap;
    }

    /**
     * Write the results for the topic with the given ID.
     */
    public void writeTopicResults(int topicID, DocHitMap results) {
        List<Hit> sortedResults =
            results.getSortedHits(new LengthScoreComparator());

        writeResultList(topicID, sortedResults);
    }

    /**
     * Write the given list of results in the order of the list.
     * This will write all the results in the list, so if you want to write
     * only the first few results, use {@link List#subList(int, int)}
     * before calling this method.
     * 
     * @param topicID
     *      use this as the topic identifier.
     */
    public void writeResultList(int topicID, List<Hit> sortedResults) {
        
        println("  <topic topic-id='" + topicID + "'>");
        
        int count = 0;
        int rank = 0;
        float lastScore = 0;
        final List<Assessable> sanitizedHits = new ArrayList<Assessable>(sortedResults.size());
        final boolean haveAssessment = assessorMap != null && assessorMap.containsKey(topicID);
        final XCGAssessor assessor = haveAssessment ? assessorMap.get(topicID) : null; 
        for (Hit hit : sortedResults) {
            
            // determine the rank
            if (hit.getScore() != lastScore) {
                rank = count + 1;
            }
            
            // determine the INEX version of the file name
            final String fileName = pathSanitizer.sanitize(hit.getFile());
            
            // write the hit
            float score = hit.getScore();
            if (hit.getContentLength() < MIN_LENGTH) {
                log.warn("Including short result " + hit);
            }
            println("    <result>");
            println("      <file>" + fileName + "</file>");
            println("      <path>" + hit.getXPath() + "</path>");
            println("      <rank>" + rank + "</rank>");
            println("      <rsv>" + score + "</rsv>");
            println("    </result>");
            
            count++;
            lastScore = hit.getScore();
            
            if (haveAssessment) {
                sanitizedHits.add(assessor.getAssessable(fileName, hit.getXPath()));
            }
        }
        
        println("  </topic>");
        writer.flush();

        if (haveAssessment) {
            final double[] nxcg = assessor.assessUpTo(sanitizedHits, RESULT_COUNT);
            println("<!--");
            for (int i = 0; i < nxcg.length; i++) {
                println("assessment " + topicID + " " + (i+1) + " " + nxcg[i]);
                nxcgSum[i] += nxcg[i];
            }
            println("-->");
            topicCount++;
            writer.flush();
        }
    }

    private void println(String string) {
        writer.println(string);
    }
    
    public void close() {
        if (topicCount > 0) {
            println("<!--");
            for (int i = 0; i < nxcgSum.length; i++) {
                println("assessment avg " + (i+1) + " " + nxcgSum[i] / topicCount);
            }
            println("-->");
        }
        println("</inex-submission>");
        writer.close();
    }
}
/*
Copyright (c) 2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/